package com.xty.xtyle.detail;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.TextureView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.xty.xtyle.R;
import com.xty.xtyle.db.ClothTypes;
import com.xty.xtyle.db.ClothTypesDao;
import com.xty.xtyle.db.User;
import com.xty.xtyle.db.UserDao;
import com.xty.xtyle.db.cloth.Cloth;
import com.xty.xtyle.event.FreshClothEvent;
import com.xty.xtyle.picture.PickPhotoDialog;
import com.xty.xtyle.utils.CommonUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

import static com.xty.xtyle.picture.PickPhotoDialog.SELECT_PIC_BY_TACK_PHOTO;
import static org.litepal.LitePalApplication.getContext;


public class AddClothActivity extends AppCompatActivity  implements EasyPermissions.PermissionCallbacks {

    /**
     * 如果为空，表示普通增加衣服
     * 如果不为空，表示用户自行添加衣服到自己的衣架
     * @param type  衣服的类型，通过首页进入
     */
    public static void startActivity(Context context, String type) {
        Intent intent = new Intent(context, AddClothActivity.class);
        if (!TextUtils.isEmpty(type)) intent.putExtra("type", type);
        context.startActivity(intent);
    }

    String clothType;
    EditText edit_brand, edit_color, edit_material, edit_size, edit_session, edit_status, edit_price, edit_type;
    ImageView imageView;
    String clothPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cloth_add);

        initBar();
        Intent intent = getIntent();
        if (null != intent) {
            clothType = intent.getStringExtra("type");
            if (!TextUtils.isEmpty(clothType)) edit_type.setText(clothType);
        }

        findViewById(R.id.right_icon).setVisibility(View.INVISIBLE);
    }

    //初始化UI
    void initBar() {
        findViewById(R.id.left_icon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        findViewById(R.id.cloth_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addCloth();
            }
        });
        findViewById(R.id.cloth_icon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkPermission();
            }
        });
        edit_brand = findViewById(R.id.edit_brand);
        edit_color = findViewById(R.id.edit_color);
        edit_material = findViewById(R.id.edit_material);
        edit_size = findViewById(R.id.edit_size);
        edit_session = findViewById(R.id.edit_session);
        edit_status = findViewById(R.id.edit_status);
        edit_price = findViewById(R.id.edit_price);
        edit_type = findViewById(R.id.edit_type);
        imageView = findViewById(R.id.cloth_icon);

    }

    void loadImage(String imagePath) {
        clothPath = imagePath;
        Glide.with(this).load(imagePath).into(imageView);
    }

    //添加衣服到数据库
    void addCloth() {
        String brand = edit_brand.getText().toString();
        String color = edit_color.getText().toString();
        String material = edit_material.getText().toString();
        String size = edit_size.getText().toString();
        String session = edit_session.getText().toString();
        String status = edit_status.getText().toString();
        String price = edit_price.getText().toString();
        String type = edit_type.getText().toString();

        Cloth cloth = new Cloth();
        cloth.setBrand(brand);
        cloth.setColor(color);
        cloth.setMaterial(material);
        cloth.setSize(size);
        cloth.setSession(session);
        cloth.setStatus(status);
        cloth.setPrice(price);
        cloth.setType(type);
        if (TextUtils.isEmpty(clothPath)){
            CommonUtil.showToast("请选择图片");
            return;
        }
        cloth.setImage(clothPath);
        checkType(type);
        //如果type不为空，表示首页进入
        if (!TextUtils.isEmpty(type)) {
            cloth.setType(type);
            //如果空的，表示用户给自己衣架添加
        } else {
            UserDao dao = new UserDao();
            User user = dao.findFirst();
            if (null != user) cloth.setUserName(user.getName());
        }
        cloth.save();
        EventBus.getDefault().post(FreshClothEvent.getInstance(1));
        CommonUtil.showToast("保存成功");
    }

    /**
     * 如果类型没有，则添加
     * @param type
     */
    void checkType(String type) {
        if (!TextUtils.isEmpty(type)) {
            ClothTypesDao clothTypesDao = new ClothTypesDao();
            ClothTypes types = clothTypesDao.findClothType(type);
            if (null == types) {
                ClothTypes clothTypes = new ClothTypes(type);
                clothTypes.save();
            }
        }
    }

    PickPhotoDialog pickPhotoDialog;
    private void showDialog() {
        pickPhotoDialog = new PickPhotoDialog();
        pickPhotoDialog.show(getSupportFragmentManager(), "pick");
        pickPhotoDialog.setCallBack(new PickPhotoDialog.CallBack() {
            @Override
            public void pictureBack(String imagePath) {
                Log.d("FlutterPush", "back  imageFile:"+imagePath);
                if (!TextUtils.isEmpty(imagePath))
                    loadImage(imagePath);
            }
        });
    }

    //拍照,图片存储/读取都要权限
    private void checkPermission() {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            showDialog();
        } else {
            //权限拒绝 申请权限
//            EasyPermissions.requestPermissions(this, getString(R.string.permission_rationale_message), 101, perms);
            ActivityCompat.requestPermissions(this, perms, 102);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        //获取的权限一定要是读取存储和照相
        String[] permss = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(getContext(), permss)) {
            showDialog();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }


//    @Route(path = BaseConstants.LIBRARY_EVENT_BUS_ACTIVITY2)
//    public class EventBusActivity2 extends CommonActivity<ActivityEventBus2Binding> {
//
//        @Override
//        protected void doCreateView(Bundle savedInstanceState) {
//            getBinding().btnPublish.setOnClickListener(v -> publishContent());
//        }
//
//        private void publishContent() {
//            String msg = getBinding().etMessage.getText().toString();
//            EventBus.getDefault().post(MessageWrap.getInstance(msg));
//            ToastUtils.makeToast("Published : " + msg);
//        }
//    }

}
